package com.gismore.jsonp.core;

import com.gismore.jsonp.config.AppConfig;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Log4j2
public class Transformer {
	public static String transform(List<SongVO> songList){
		List<String> retList = Lists.newArrayList();
		String toDirectory = AppConfig.me().toDirectory();
		Long startTime = System.currentTimeMillis();
		log.info("开始转换歌曲数据...");
		songList
				.forEach(song->{
					File searchDirectory = new File (toDirectory , song.getArtistName() +File.separator + song.getAlbumTitle());
					if(!searchDirectory.exists()){
						if(Strings.EMPTY.equals(song.getAlbumTitle())){
							searchDirectory.mkdir();
						}else{
							searchDirectory.mkdirs();
						}
					}
					File songFile = new File(searchDirectory, song.getFileName());
					if(!songFile.exists()){
						File rawSongFile = new File(song.getFilePath());
						if(rawSongFile.exists()){
							try {
								log.info("开始拷贝歌曲【{}】到目标位置:{}",song.getFileName(),searchDirectory);
								songFile.createNewFile();
								Long copyStartTime = System.currentTimeMillis();
								Files.copy(rawSongFile, songFile);
								Long copyEndTime = System.currentTimeMillis();
								log.info("歌曲【{}】拷贝成功，耗时{}ms",song.getFileName(), copyEndTime - copyStartTime );
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
					if(songFile.exists()){
						retList.add(StringUtils.substringAfter(songFile.getPath(), toDirectory));
					}
				});
		log.info("歌曲数据转换完成，耗时{}ms.", System.currentTimeMillis() - startTime);
		return retList.stream().collect(Collectors.joining(System.lineSeparator()));
	}

	private static File getFile(File searchFile, String fileName) {
		if(!searchFile.exists()){
			return null;
		}
		File[] arr = searchFile.listFiles();
		File retFile = null;
		if(arr != null){
			for (File file : arr) {
				if (file.isDirectory()) {
					retFile = getFile(file,fileName);
					break;
				} else {
					if(file.getName().equals(fileName)){
						retFile = file;
						break;
					}
				}
			}
		}
		return retFile;
	}
}
